<template>
	<div class="uploadSimple">
		<van-loading v-if="loading" text-color="#fff" vertical class="customLoading"
			>加载中...</van-loading
		>
		<img ref="image" style="visibility: hidden" :src="captureData" class="camera-preview" />
		<van-uploader
			ref="uploadSimple"
			:after-read="afterRead"
			:show-upload="true"
			:preview-image="false"
		></van-uploader>
		<div class="camera-capture" v-if="isUpload">
			<div class="cancel" @click="cancel">取消</div>
			<div class="sure" @click="submit">确认</div>
		</div>
	</div>
</template>

<script>
import { Uploader } from 'vant';
import Cropper from 'cropperjs'
import 'cropperjs/dist/cropper.css'
import Compressor from 'compressorjs'
import { get_ocr } from '@/api/PGXT'
export default {
	name: 'upload',
	components: {
		'van-uploader':Uploader
	},
	props: {
		isRefresh: {
			type: Boolean,
			default: true
		}
	},
	data() {
		return {
			loading: false,
			isUpload: false,
			captureData: '',
			cropper: null
		}
	},
	methods: {
		cancel() {
			this.captureData = ''
			this.$emit('updateCom', false)
			this.loading = false
			if (this.isRefresh) {
				this.$router.go(0)
			}
		},
		// beforeRead(){
		// 	this.$emit('updateLoading',true)
		// },
		afterRead(val) {
			console.log('val', val)
			this.loading = true
			this.$emit('updateCom', true)
			this.imgPreview(val.file, val.content)
		},
		handleImg(file) {
			let self = this
			console.log('压缩前', file.size)
			if (file.size > 2 * 1024 * 1024) {
				console.log('压缩')
				// 判断图片大小是否大于2M
				new Compressor(file, {
					quality: 0.6, // 压缩质量
					success(result) {
						console.log('result', result)
						// 压缩成功后，将压缩后的图片转为base64并返回
						const reader = new FileReader()
						reader.readAsDataURL(result)
						reader.onload = () => {
							const base64 = reader.result
							self.getIdCardByOCR(base64)
							// self.captureData = base64
							// setTimeout(() => {
							// 	self.getImgByCropper()
							// }, 2000)
						}
					},
					error(err) {
						console.log(err.message)
					}
				})
			} else {
				const reader = new FileReader()
				reader.readAsDataURL(file)
				reader.onload = () => {
					const base64 = reader.result
					self.getIdCardByOCR(base64)
					// self.captureData = base64
					// setTimeout(() => {
					// 	self.getImgByCropper()
					// }, 2000)
				}
			}
		},
		compress(img) {
			console.log('传入img', img)
			let canvas = document.createElement('canvas')
			let ctx = canvas.getContext('2d')
			//瓦片canvas
			let tCanvas = document.createElement('canvas')
			let tctx = tCanvas.getContext('2d')
			// let initSize = img.src.length;
			let width = img.width
			let height = img.height
			//如果图片大于四百万像素，计算压缩比并将大小压至400万以下
			let ratio
			if ((ratio = (width * height) / 4000000) > 1) {
				// console.log("大于400万像素");
				ratio = Math.sqrt(ratio)
				width /= ratio
				height /= ratio
			} else {
				ratio = 1
			}
			canvas.width = width
			canvas.height = height
			// 铺底色
			ctx.fillStyle = '#fff'
			ctx.fillRect(0, 0, canvas.width, canvas.height)
			//如果图片像素大于100万则使用瓦片绘制
			let count
			if ((count = (width * height) / 1000000) > 1) {
				count = ~~(Math.sqrt(count) + 1) //计算要分成多少块瓦片
				//            计算每块瓦片的宽和高
				let nw = ~~(width / count)
				let nh = ~~(height / count)
				tCanvas.width = nw
				tCanvas.height = nh
				for (let i = 0; i < count; i++) {
					for (let j = 0; j < count; j++) {
						tctx.drawImage(
							img,
							i * nw * ratio,
							j * nh * ratio,
							nw * ratio,
							nh * ratio,
							0,
							0,
							nw,
							nh
						)
						ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh)
					}
				}
			} else {
				ctx.drawImage(img, 0, 0, width, height)
			}
			//进行最小压缩
			let ndata = canvas.toDataURL('image/jpeg', 0.2)
			tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0
			return ndata
		},
		async getIdCardByOCR(base64) {
			let res = await get_ocr({ ocrType: 'idcard', imgString: base64 })
			if (res.status == 1 && res.id) {
				let obj = {
					idCard: res.id || '',
					name: res.name || '',
					sex: res.sex || '',
					nation: res.nation || '',
					address: res.address || '',
					birthDate: res.birth_date || ''
				}
				this.$emit('sureIdCard', obj)
				this.loading = false
			} else {
				this.loading = false
				this.$toast.fail('身份证信息扫描失败，请重新拍照上传！')
			}
		},
		base64ToFile(base64Data, fileName) {
			const byteCharacters = atob(base64Data)
			const byteNumbers = new Array(byteCharacters.length)
			for (let i = 0; i < byteCharacters.length; i++) {
				byteNumbers[i] = byteCharacters.charCodeAt(i)
			}
			const byteArray = new Uint8Array(byteNumbers)
			const file = new File([byteArray], fileName, { type: 'image/png' })
			return file
		},
		submit() {
			this.loading = true
			// 获取裁剪后的图片的 base64 格式
			const croppedCanvas = this.cropper.getCroppedCanvas({
				// width: 100,
				// height: 196,
				// left: 600,
				// top: 948
			})
			const croppedBase64 = croppedCanvas.toDataURL()

			this.rotateImg(croppedBase64)
			// console.log('res', res)
		},
		getImageSizeFromBase64(base64) {
			const byteCharacters = atob(base64.split(',')[1])
			const byteNumbers = new Array(byteCharacters.length)
			for (let i = 0; i < byteCharacters.length; i++) {
				byteNumbers[i] = byteCharacters.charCodeAt(i)
			}
			const byteArray = new Uint8Array(byteNumbers)
			const blob = new Blob([byteArray], { type: 'image/jpeg' })
			return blob.size
		},

		rotateImg(base64) {
			let self = this
			var img = new Image()
			img.src = base64
			img.onload = function () {
				var canvas = document.createElement('canvas')
				var ctx = canvas.getContext('2d')
				canvas.width = img.height
				canvas.height = img.width
				ctx.translate(0, img.width)
				ctx.rotate((-90 * Math.PI) / 180)
				ctx.drawImage(img, 0, 0)
				var rotatedBase64 = canvas.toDataURL()
				// 返回旋转后的base64
				// console.log('rotatedBase64', rotatedBase64)
				// self.captureData = rotatedBase64
				let file = self.dataURLtoFile(rotatedBase64)
				// let size = self.getImageSizeFromBase64(rotatedBase64)
				self.handleImg(file)
			}
		},
		dataURLtoFile(dataurl) {
			var arr = dataurl.split(',')
			var bstr = atob(arr[1])
			var n = bstr.length
			var u8arr = new Uint8Array(n)
			while (n--) {
				u8arr[n] = bstr.charCodeAt(n)
			}
			return new File([u8arr], 'idCard', {
				type: 'image/jpeg'
			})
		},
		getImgByCropper() {
			let self = this
			// 初始化 Cropper.js
			this.cropper = new Cropper(this.$refs.image, {
				aspectRatio: 1 / 1.58, //默认比例
				// autoCropArea: 0.8,
				initialAspectRatio: 0.6667,
				cropBoxResizable: true,
				cropBoxMovable: true,
				dragMode: 'none',
				ready: function () {
					self.captureData = ''
					self.loading = false
				},
				crop: (event) => {
					console.log(event)
				}
			})
		},
		imgPreview(file, base64) {
			this.isUpload = true
			this.captureData = base64
			setTimeout(() => {
				this.getImgByCropper()
			}, 2000)
		}
	}
}
</script>
<style lang="less" scoped>
.uploadSimple {
	position: fixed;
	left: 0;
	top: 0;
	width: 100vw;
	height: 100vh;
	overflow: hidden;
	z-index: 9;
}
.camera-preview {
	position: fixed;
	left: -100%;
	bottom: -100%;
}
.camera-capture {
	z-index: 9;
	width: 100vw;
	position: fixed;
	left: 50%;
	transform: translateX(-50%);
	bottom: 10%;
	.cancel {
		position: absolute;
		left: 20%;
		color: #fff;
		font-size: 36px;
	}
	.sure {
		position: absolute;
		left: 70%;
		color: #fff;
		font-size: 36px;
	}
	div {
		margin: 0 10px;
	}
}
/deep/ .van-uploader {
	position: fixed;
	left: -100%;
	bottom: -100%;
}
.customLoading {
	z-index: 99;
	position: absolute !important;
	left: 50%;
	top: 50%;
	transform: translate(-50%, -50%);
}
</style>
